package com.itheima.timer;

import com.itheima.dao.SeckillGoodsMapper;
import com.itheima.entity.DateUtil;
import com.itheima.entity.SystemConstants;
import com.itheima.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 版权：(C) 版权所有 2000-2020 上海天好电子商务有限公司苏州分公司
 * <简述>
 * <详细描述>
 *
 * @author LiuShanshan
 * @version $Id$
 */
@Component
public class SeckillGoodsPushTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    /****
     * 每4秒执行一次
     * 改造：从数据库中查询数据，放入redis中。放入redis中时，进行校验
     */
    //@Scheduled(cron = "0/4 * * * * ?")
    public void loadGoodsPushRedisSife(){
        //1.获取当前的时间对应的5个时间段
        List<Date> dateMenus = DateUtil.getDateMenus();
        // 获取时间间隔，切过滤掉redis数据中已经存在的数据
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        dateMenus.forEach(x -> {
            String[] split = simpleDateFormat.format(x).split("-");
            String dateSection = split[0] + split[1] + split[2];
            Boolean exist = redisTemplate.hasKey(SystemConstants.SEC_KILL_GOODS_PREFIX + ":" + dateSection);
            if(!exist){
                dateList.add(simpleDateFormat.format(x));
            }
        });
        List<SeckillGoods> seckillGoods = new ArrayList<>();
        if(dateList.size() > 0){
            // 查询mysql数据数据中
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");
            criteria.andGreaterThan("stockCount",0);
            criteria.andGreaterThanOrEqualTo("startTime",dateList.get(0));
            criteria.andLessThan("endTime",dateList.get(dateList.size() -1));
            seckillGoods = seckillGoodsMapper.selectByExample(example);
        }
        // 将数据放入redis中
        // todo 无法知道时间区域
        if(seckillGoods.size() > 0){
//            redisTemplate.boundHashOps()
        }
    }

    //反复被执行的方法 隔5秒钟执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    public void loadGoodsPushRedis() throws ParseException {
        //1.获取当前的时间对应的5个时间段
        List<Date> dateMenus = DateUtil.getDateMenus();
        //2.循环遍历5个时间段 获取到时间的日期
        for (Date starttime : dateMenus) {

            //2019090516
            String extName =  DateUtil.data2str(starttime,DateUtil.PATTERN_YYYYMMDDHH);
            //3.将循环到的时间段 作为条件 从数据库中执行查询 得出数据集


            /**
             * select * from tb_seckill_goods where
             stock_count>0
             and `status`='1'
             and start_time > 开始时间段
             and end_time < 开始时间段+2hour  and id  not in (redis中已有的id)
             */



            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");
            criteria.andGreaterThan("stockCount",0);
            criteria.andGreaterThanOrEqualTo("startTime",starttime);
            criteria.andLessThan("endTime",DateUtil.addDateHour(starttime, 2));

            //排除掉redis已有的商品
            Set keys = redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + extName).keys();
            if(keys!=null && keys.size()>0) {
                criteria.andNotIn("id", keys);
            }

            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);

            //4.将数据集存储到redis中(key field value的数据格式 )

            /**
             * key(时间段
             :2019090516)     field (id:1)   value(商品的数据pojo)
             field (id:2)   value(商品的数据pojo)

             key(时间段:2019090518)      field (id:3)   value(商品的数据pojo)

             field (id:4)   value(商品的数据pojo)

             *
             *
             */

            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + extName).put(seckillGood.getId(),seckillGood);
                //设置有效期
                redisTemplate.expireAt(SystemConstants.SEC_KILL_GOODS_PREFIX + extName,DateUtil.addDateHour(starttime, 2));
            }


        }
}}
